import _ from 'lodash'

/**
 * @example
 * createMaps([{id: 1, name: 'names'}]) =>
 * {1: 'names'}
 * createDeepMaps([{id: 1, name: 'names', sub: [
 * {id: 2, name: 'deep-names', sub: []},
 * {id: 3, name: 'deep-names2'}
 * ]}]) =>
 * {1: 'names',2: 'deep-names',3: 'deep-names2'}
 */

function createMapsDeepFunc (arr, key, value, sub, maps, isDeep) {
  _.each(arr, item => {
    maps[item[key]] = item[value]
    if (isDeep) {
      if (item[sub] && item[sub].length) {
        createMapsDeepFunc(item[sub], key, value, sub, maps, isDeep)
      }
    }
  })
}

export const createMaps = (arr, key, value, sub, isDeep) => {
  let _maps = {}
  let _key = key || 'id'
  let _value = value || 'name'
  let _sub = sub || 'sub'
  let _isDeep = isDeep || false
  if (_.isEmpty(_maps)) {
    createMapsDeepFunc(arr, _key, _value, _sub, _maps, _isDeep)
  }
  return _maps
}

export const createDeepMaps = (arr, key, value, sub) => {
  return createMaps(arr, key, value, sub, true)
}

/**
 * 遍历地区数据，如果pid 为 0 说明为顶级，需要清空cache
 * cache 用于缓存，父级数据值
 * 遍历到最后一级时，重置删除cache，index === 1 之后的数据，list.length - 1 === index
 */
const eachSub = (list, maps, cache, value, hasAll) => {
  _.each(list, (item, index, source) => {
    if (item.sub) {
      if (item.pid === '0') {
        cache.length = 0
      }
      // 是否包含item自身, 这里删除sub
      if (hasAll) {
        maps[item.id] = cache.concat(item[value])
      }
      cache.push(item[value])
      eachSub(item.sub, maps, cache, value, hasAll)
    } else {
      maps[item.id] = cache.concat(item[value])
      if (source.length - 1 === index) {
        cache.length = 1
      }
    }
  })
}
/**
 * createDeepToRootValuesMaps
 * 创建Maps {id: [根节点值, 父节点值, 自身节点值]}
 * @exmple
 [
 {id: '1', name: 'name', sub: [
 {id: '2', name: 'name2', sub: [...]}
 ]}
 ] => {[2: [根节点值, 父节点值, 自身节点值]}
 * @return maps {object}
 */
export const createDeepToRootValuesMaps = (list, value, hasAll) => {
  let maps = {}
  let cache = []
  let _value = value || 'id' // id 对应的值，默认id，name, pid
  let _hasAll = hasAll || false
  eachSub(list, maps, cache, _value, _hasAll)
  return maps
}
